package com.cap.bts.crmdp.dealer.masterinfo.dao.impl;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.hibernate.Session;
import org.hibernate.engine.SessionFactoryImplementor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.cap.bts.crmdp.dealer.masterinfo.dao.ITyreProductDao;
import com.cap.bts.crmdp.dealer.masterinfo.domain.TyreProductModel;
import com.cap.bts.framework.common.dao.callback.NativeQueryJpaCallback;
import com.cap.bts.framework.common.dao.impl.BaseDaoImpl;
import com.cap.bts.framework.common.exception.AppException;

@Repository("iTyreProductDao")
public class TyreProductDaoImpl extends BaseDaoImpl<TyreProductModel, Long> implements
                                                                           ITyreProductDao {
//	private static final Logger LOGGER = Logger.getLogger(TyreProductDaoImpl.class);
    @Inject
    public TyreProductDaoImpl(@Value("com.cap.bts.crmdp.dealer.masterinfo.domain.TyreProductModel") Class<TyreProductModel> clazz) {
        super(clazz);

    }
/*
    @Override
    public TyreProductModel insertTyreProductInfo(TyreProductModel tyreProductModel)
                                                                                    throws AppException {
        return save(tyreProductModel);
    }*/

  /*  @Override
    public void removeTyreProduct(TyreProductModel tyreProductModel) throws AppException {
        remove(tyreProductModel);
    }*/

    @Override
    public List<TyreProductModel> getAllTyreProduct() throws AppException {
        String selectStr = "select * from tm_tyre_product a";
        // 查询结果集的SQL
        StringBuilder selectSql = new StringBuilder();

        StringBuilder where = new StringBuilder();
        where.append(" where 1=1 ");

        selectSql.append(selectStr).append(where.toString());

        return super.getJpaTemplate().execute(
            new NativeQueryJpaCallback<TyreProductModel>(selectSql.toString(),
                TyreProductModel.class));
    }

   /* @Override
    public void removeAllTyreProductInfo() throws AppException {
        String selectStr = "delete from tm_tyre_product";
        removeByQuery(selectStr);
    }*/

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年10月27日
     * @see com.cap.bts.crmdp.dealer.masterinfo.dao.ITyreProductDao#getViewForTyre(java.lang.String)
    **/
    @Override
    public List<TyreProductModel> getViewForTyre(String sql) throws AppException {
        return this.getListByNativeQuery(sql);
    }

    /**
     * 根据编号查询信息
     * @see com.cap.bts.crmdp.dealer.masterinfo.dao.ITyreProductDao#getTyreProductList(java.lang.String)
     */
   /* @Override
    public List<TyreProductModel> getTyreProductList(String mfgrCode) throws AppException {
        String sqlString = "select * from tm_tyre_product where MFGRCODE=?1";

        return super.getListByNativeQueryWithVaParam(sqlString,
            mfgrCode);
    }*/

    /*@Override
    public boolean updateTyreProductInfo(TyreProductModel tyreProductModel, Long id)
                                                                                    throws AppException {
        TyreProductModel tyreProductModel2 = findById(id);
        tyreProductModel2.setPartType(tyreProductModel.getPartType());
        tyreProductModel2.setMfgrNo(tyreProductModel.getMfgrNo());
        tyreProductModel2.setNameCn(tyreProductModel.getNameCn());
        tyreProductModel2.setNameEn(tyreProductModel.getNameEn());
        tyreProductModel2.setBrandNameCN(tyreProductModel.getBrandNameCN());
        tyreProductModel2.setBrandNameEN(tyreProductModel.getBrandNameEN());
        tyreProductModel2.setSeriesNameCN(tyreProductModel.getSeriesNameCN());
        tyreProductModel2.setSeriesNameEN(tyreProductModel.getSeriesNameEN());
        tyreProductModel2.setVehicleType(tyreProductModel.getVehicleType());
        tyreProductModel2.setSizeDesc(tyreProductModel.getSizeDesc());
        tyreProductModel2.setSize(tyreProductModel.getSize());
        tyreProductModel2.setSizeType(tyreProductModel.getSizeType());
        tyreProductModel2.setSizeUnit(tyreProductModel.getSizeUnit());
        tyreProductModel2.setSalesType(tyreProductModel.getSalesType());
        tyreProductModel2.setPriceref(tyreProductModel.getPriceref());
        tyreProductModel2.setRemark(tyreProductModel.getRemark());
        tyreProductModel2.setDescription(tyreProductModel.getDescription());
        tyreProductModel2.setAttrPlt(tyreProductModel.getAttrPlt());
        tyreProductModel2.setAttrPattrn(tyreProductModel.getAttrPattrn());
        tyreProductModel2.setAttrDimWidth(tyreProductModel.getAttrDimWidth());
        tyreProductModel2.setAttrDimRatio(tyreProductModel.getAttrDimRatio());
        tyreProductModel2.setAttrDimDiameter(tyreProductModel.getAttrDimDiameter());
        tyreProductModel2.setAttrStructure(tyreProductModel.getAttrStructure());
        tyreProductModel2.setAttrDimLoadIndex(tyreProductModel.getAttrDimLoadIndex());
        tyreProductModel2.setAttrDimSpeedIndex(tyreProductModel.getAttrDimSpeedIndex());
        tyreProductModel2.setAttrSpecialMarking(tyreProductModel.getAttrSpecialMarking());
        tyreProductModel2.setAttrSeasonWinter(tyreProductModel.getAttrSeasonWinter());
        tyreProductModel2.setAttrRft(tyreProductModel.getAttrRft());

        update(tyreProductModel2);

        return true;
    }*/

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年12月1日
     * @see com.cap.bts.crmdp.dealer.masterinfo.dao.ITyreProductDao#getTyreProductInfoByMfgrCode(java.lang.String)
    **/
  /*  @Override
    public List<TyreProductModel> getTyreProductInfoByMfgrCode(String mfgrCode) throws AppException {
        String sql = "select * from tm_tyre_product where MFGRCODE = '" + mfgrCode + "'";
        return this.getListByNativeQuery(sql);
    }*/
    
    
    
    @Override
    public void batchInsert(List<TyreProductModel> productDataList) throws AppException{
    	Session session = (org.hibernate.Session) getEntityManager().getDelegate();
		SessionFactoryImplementor sf = (SessionFactoryImplementor) session.getSessionFactory();
		Connection connection = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmtDel = null;
		String batchId = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_" + ((int) (Math.random() * (99999 - 10000 + 1)) + 10000);
		try{
			connection = sf.getConnectionProvider().getConnection();
			connection.setAutoCommit(false);
			
			String sql ="INSERT INTO tm_tyre_product (  " +
					"  PARTTYPE,  " +
					"  MFGRCODE,  " +
					"  MFGRNO,  " +
					"  NAMECN,  " +
					"  NAMEEN,  " +
					"  BRANDNAMECN,  " +
					"  BRANDNAMEEN,  " +
					"  SERIESNAMECN,  " +
					"  SERIESNAMEEN,  " +
					"  VEHICLETYPE,  " +
					"  SIZEDESC,  " +
					"  SIZE,  " +
					"  SIZETYPE,  " +
					"  SIZEUNIT,  " +
					"  SALESTYPE,  " +
					"  PRICEREF,  " +
					"  REMARK,  " +
					"  DESCRIPTION,  " +
					"  ATTRPLT,  " +
					"  ATTRPATTRN,  " +
					"  ATTRDIMWIDTH,  " +
					"  ATTRDIMRATIO,  " +
					"  ATTRDIMDIAMETER,  " +
					"  ATTRSTRUCTURE,  " +
					"  ATTRDIMLOADINDEX,  " +
					"  ATTRDIMSPEEDINDEX,  " +
					"  ATTRSPECIALMARKING,  " +
					"  ATTRSEASONWINTER,  " +
					"  ATTRRFT,  " +
					"  CREATE_BY,  " +
					"  CREATE_DATE,  " +
					"  LAST_UPDATE_BY,  " +
					"  LAST_UPDATE_DATE,  " +
					"  BATCH_ID  " +
					")  " +
					"VALUES  " +
					"  (  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?,  " +
					"    ?  " +
					"  ) " ;;
			
			pstmt = connection.prepareStatement(sql);
			
			Timestamp time = new Timestamp(new Date().getTime());
			int i = 0;
			for (TyreProductModel dto : productDataList) {
				i++;
				
				pstmt.setString(1, dto.getPartType());
				pstmt.setString(2, dto.getMfgrCode());
				pstmt.setString(3, dto.getMfgrNo());
				pstmt.setString(4, dto.getNameCn());
				pstmt.setString(5, dto.getNameEn());
				pstmt.setString(6, dto.getBrandNameCN());
				pstmt.setString(7, dto.getBrandNameEN());
				pstmt.setString(8, dto.getSeriesNameCN());
				pstmt.setString(9, dto.getSeriesNameEN());
				pstmt.setString(10, dto.getVehicleType());
				pstmt.setString(11, dto.getSizeDesc());
				pstmt.setString(12, dto.getSize());
				pstmt.setString(13, dto.getSizeType());
				pstmt.setString(14, dto.getSizeUnit());
				pstmt.setString(15, dto.getSalesType());
				pstmt.setString(16, dto.getPriceref());
				pstmt.setString(17, dto.getRemark());
				pstmt.setString(18, dto.getDescription());
				pstmt.setString(19, dto.getAttrPlt());
				pstmt.setString(20, dto.getAttrPattrn());
				pstmt.setString(21, dto.getAttrDimWidth());
				pstmt.setString(22, dto.getAttrDimRatio());
				pstmt.setString(23, dto.getAttrDimDiameter());
				pstmt.setString(24, dto.getAttrStructure());
				pstmt.setString(25, dto.getAttrDimLoadIndex());
				pstmt.setString(26, dto.getAttrDimSpeedIndex());
				pstmt.setString(27, dto.getAttrSpecialMarking());
				pstmt.setString(28, dto.getAttrSeasonWinter());
				pstmt.setString(29, dto.getAttrRft());
				pstmt.setInt(30, 0);
				pstmt.setTimestamp(31, time);
				pstmt.setInt(32, 0);
				pstmt.setTimestamp(33, time);
				pstmt.setString(34, batchId);
				
				pstmt.addBatch();
				
				if(i%30000 == 0){
					pstmt.executeBatch();     
					connection.commit();     
					pstmt.clearBatch(); 
				}
				
			}
		
			if(i%30000 != 0){
				pstmt.executeBatch();     
				connection.commit();     
			}
			
			
			String delSql = "delete from tm_tyre_product where BATCH_ID <> ? or BATCH_ID is null";
			
			pstmtDel =  connection.prepareStatement(delSql);
			pstmtDel.setString(1, batchId);
			pstmtDel.executeUpdate();
			
			
			String initSql = "{call prc_item_master_update()}";
			
			CallableStatement callableStatement = connection.prepareCall(initSql);
			callableStatement.executeUpdate();
			callableStatement.close();
			
			connection.commit();
			
		}catch(Exception e){
			try {
				connection.rollback();
			} catch (SQLException e1) {
				logger.error("", e1);
			}
			throw new AppException("ERROR", e);
		}finally{
			try {
				if(connection != null){
					connection.setAutoCommit(true);
					pstmt.close();
					if(pstmtDel != null){
						pstmtDel.close();
					}
					connection.close();
				}
			} catch (SQLException e) {
				logger.error("", e);
				pstmt = null;
				pstmtDel = null;
				connection = null;
			}
		}
    	
    	
    	
    }
    
}
